<template>
  <div class="p-3">
    <a-card>
      <a-row :gutter="[32, 8]">
        <a-col :span="24">
          <a-tabs v-model:activeKey="activeKey" @change="changeTab">
            <a-tab-pane key="1" tab="盘点">
              <p class="text-lg font-bold">盘点单</p>
              <vxe-form
                title-colon
                ref="formRef"
                title-align="right"
                title-width="100"
                @submit="submitEvent"
                @reset="resetEvent($event)"
                :data="formData"
                :rules="formRules"
              >
                <vxe-form-gather span="24">
                  <vxe-form-item title="盘点人" field="user_id" span="4">
                    <template #default="{ data }">
                      <vxe-select
                        v-model="data.user_id"
                        placeholder="请选择盘点人"
                      >
                        <vxe-option
                          v-for="(g, index) in searchTableOpt.userOpt"
                          :label="g.label"
                          :value="g.id"
                          :key="index"
                        >
                        </vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="单位" field="site_id" span="4">
                    <template #default="{ data }">
                      <vxe-select
                        v-model="data.site_id"
                        placeholder="请选择单位"
                        @change="changeSite"
                      >
                        <vxe-option
                          v-for="(g, index) in searchTableOpt.siteOpt"
                          :label="g.label"
                          :value="g.id"
                          :key="index"
                        >
                        </vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="部门" field="department_id" span="4">
                    <template #default="{ data }">
                      <vxe-select
                        v-model="data.department_id"
                        placeholder="请选择部门"
                      >
                        <vxe-option
                          v-for="(g, index) in searchTableOpt.departmentOpt"
                          :label="g.label"
                          :value="g.id"
                          :key="index"
                        >
                        </vxe-option>
                      </vxe-select>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item
                    title="单据编号"
                    field="purchase_order_no"
                    span="4"
                  >
                    <template #default="{ data }">
                      <vxe-input
                        v-model="data.inventorycount_no"
                        placeholder="请输入单据编号"
                      ></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="商品" field="receipt_items" span="24">
                    <template #default="{ data }">
                      <vxe-toolbar ref="toolbarRef" print export> </vxe-toolbar>
                      <!--              table-->
                      <vxe-table
                        border
                        show-overflow
                        show-footer
                        keep-source
                        :print-config="{
                          sheetName: `${formData.inventorycount_no}`,
                        }"
                        :export-config="{
                          filename: `${formData.inventorycount_no}`,
                        }"
                        :is-hover="true"
                        :edit-rules="validRules"
                        ref="xTable"
                        :column-config="{ resizable: true }"
                        min-height="400"
                        :data="formData.inventorycountitems"
                        :footer-method="footerMethod"
                        :edit-config="{
                          trigger: 'click',
                          mode: 'row',
                          showStatus: true,
                        }"
                      >
                        <vxe-column
                          field="supplier_name"
                          title="供应商"
                          sortable
                        >
                        </vxe-column>

                        <vxe-column
                          field="supplier_id"
                          title="供应商id"
                          sortable
                        >
                        </vxe-column>
                        <vxe-column
                          field="product_name"
                          title="商品名称"
                          sortable
                        >
                        </vxe-column>

                        <vxe-column field="product_id" title="商品id" sortable>
                        </vxe-column>

                        <vxe-column
                          field="theoretical_qty"
                          title="理论数量"
                          sortable
                          :edit-render="{
                            autofocus: '.vxe-input--inner',
                            defaultValue: '',
                          }"
                        >
                          <template #edit="{ row }">
                            <!--                    使用懒加载，带搜索功能-->
                            <vxe-input
                              v-model="row.theoretical_qty"
                              type="number"
                            ></vxe-input>
                          </template>
                        </vxe-column>
                        <vxe-column
                          field="actual_qty"
                          title="实际数量"
                          sortable
                          :edit-render="{
                            autofocus: '.vxe-input--inner',
                            defaultValue: '',
                          }"
                        >
                          <template #edit="{ row }">
                            <vxe-input
                              v-model="row.actual_qty"
                              type="number"
                            ></vxe-input>
                          </template>
                        </vxe-column>
                        <vxe-column
                          field="difference_qty"
                          title="差异数量"
                          sortable
                          :edit-render="{
                            autofocus: '.vxe-input--inner',
                            defaultValue: '差异数量',
                          }"
                        >
                          <template #edit="{ row }">
                            <vxe-input
                              v-model="row.difference_qty"
                              type="number"
                              disabled
                            ></vxe-input>
                          </template>
                        </vxe-column>

                        <vxe-column
                          field="note"
                          title="备注"
                          sortable
                          :edit-render="{
                            autofocus: '.vxe-input--inner',
                            defaultValue: '默认的名字',
                          }"
                        >
                          <template #edit="{ row }">
                            <!--                    使用懒加载，带搜索功能-->
                            <vxe-input v-model="row.note"></vxe-input>
                          </template>
                        </vxe-column>
                      </vxe-table>
                      <!--              table-->
                    </template>
                  </vxe-form-item>

                  <vxe-form-gather span="16">
                    <vxe-form-item
                      title="差异数量"
                      field="difference_total"
                      span="4"
                    >
                      <template #default="{ data }">
                        <vxe-input
                          v-model="formData.difference_total"
                          placeholder="请输入数量"
                        ></vxe-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item
                      title="理论数量"
                      field="theoretical_total"
                      span="4"
                    >
                      <template #default="{ data }">
                        <vxe-input
                          v-model="formData.theoretical_total"
                          placeholder="请输入数量"
                        ></vxe-input>
                      </template>
                    </vxe-form-item>
                    <vxe-form-item
                      title="实际数量"
                      field="actual_total"
                      span="4"
                    >
                      <template #default="{ data }">
                        <vxe-input
                          v-model="formData.actual_total"
                          placeholder="请输入数量"
                        ></vxe-input>
                      </template>
                    </vxe-form-item>
                  </vxe-form-gather>
                </vxe-form-gather>

                <vxe-form-item align="left" span="24">
                  <template #default>
                    <vxe-button
                      type="submit"
                      icon="vxe-icon-save"
                      status="primary"
                      content="提交"
                    ></vxe-button>
                    <vxe-button
                      type="reset"
                      icon="vxe-icon-undo"
                      content="重置"
                    ></vxe-button>
                  </template>
                </vxe-form-item>
              </vxe-form>
            </a-tab-pane>
            <a-tab-pane key="2" tab="报损">
              <Damage />
            </a-tab-pane>
          </a-tabs>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import Api from "@/api/backend/api";
import XEUtils from "xe-utils";
import { message } from "ant-design-vue";
import Damage from "./components/damage.vue";
const activeKey = ref("1");
const changeTab = () => {};
const router = useRoute();
let formData = reactive({
  inventorycount_no:
    "PDDD-" + XEUtils.toDateString(new Date(), `yyyyMMddHHmmss`),
  user_id: null,
  site_id: null,
  department_id: null,
  theoretical_total: 0,
  actual_total: 0,
  difference_total: 0,
  note: "",
  inventorycountitems: [],
});

formData.inventorycountitems = await Api.stockController.newiestStock();

const xTable = ref();
const toolbarRef = ref();
const searchTableOpt = ref({
  supplierOpt: [],
  productOpt: [],
  userOpt: [],
});
const searchTableForm = ref({
  supplier_id: null,
  product_id: null,
});
// 表格校验
const validRules = ref<VxeTablePropTypes.EditRules>({
  theoretical_qty: [{ required: true, message: "理论数量" }],
  actual_qty: [{ required: true, message: "实际数量" }],
  difference_qty: [{ required: true, message: "差异数量" }],
});
//当站点变化时
const changeSite = async (event) => {
  const departmentOpt = await Api.departmentController.option({
    sid: event.value,
  });
  searchTableOpt.value.departmentOpt = departmentOpt;
};
watch(
  () => formData.inventorycountitems, // 监听的目标
  (newData) => {
    newData.forEach((row) => {
      row.difference_qty = row.theoretical_qty - row.actual_qty;
    });
  },
  { deep: true } // 确保深度监听数组内部的变化
);
const sumNum = (list: ReceiptItemModel[], field: string) => {
  let count = 0;
  list.forEach((item) => {
    count += item[field];
  });
  return count;
};

const countAmount = (row: ReceiptItemModel) => {
  row.qty = +row.qty;
  let mount = row.unit_price * row.qty;

  return mount;
};

const countAllAmount = (data: ReceiptItemModel[]) => {
  let count = 0;
  data.forEach((row) => {
    count = count + countAmount(row);
  });
  return count;
};



const removeSelectReceiptItem = (row) => {
  const $table = xTable.value;
  if ($table) {
    $table.removeCheckboxRow();
  }
};

const footerMethod: VxeTablePropTypes.FooterMethod<ReceiptItemModel> = ({
  columns,
  data,
}) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return `合计`;
      }
      if (columnIndex === 4) {
        //表单提交时会自动触发该事件。这个时候需要更新formData中的amount
        let count = sumNum(data, "theoretical_qty");
        formData.theoretical_total = count;
        return `数量： 共 ${count} `;
      }
      if (columnIndex === 5) {
        //表单提交时会自动触发该事件。这个时候需要更新formData中的amount
        let count = sumNum(data, "actual_qty");
        formData.actual_total = count;
        return `数量： 共 ${count} `;
      }

      if (columnIndex === 6) {
        formData.difference_total = sumNum(data, "difference_qty");
        return `数量： 共 ${sumNum(data, "difference_qty")}`;
      }
      return "-";
    }),
  ];
};

onMounted(async () => {
  const productOpt = await Api.productController.option({
    filters: {
      supplier_id: searchTableForm.value.supplier_id,
    },
  });
  const useropt = await Api.userController.option();
  const supplieropt = await Api.supplierController.option({
    filters: {
      id: null,
    },
  });
  const siteOpt = await Api.siteController.option();
  searchTableOpt.value.siteOpt = siteOpt;
  searchTableOpt.value.productOpt = productOpt;
  searchTableOpt.value.userOpt = useropt;
  searchTableOpt.value.supplierOpt = supplieropt;
  const $table = xTable.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }
});

const formRules = ref<VxeFormPropTypes.Rules>({
  supplier_name: [{ required: true, content: "请选择供货单位" }],
  user_id: [
    {
      required: true,
      content: "请选择经手人",
    },
  ],
  record_date: [{ required: true, content: "请选择制单日期" }],
});

// 提交表单
const submitEvent = async () => {
  const $table = xTable.value;
  //验证表格中的数据，如果失败则返回
  let error = await $table.validate();
  if (error) {
    message.error("数据错误，请检查");
    return;
  }
  const { tableData } = $table.getTableData();
  if (tableData.length == 0) {
    message.error("请添加商品，请检查");
    return;
  }
  formData.inventorycountitems = tableData;
  formData.theoretical_total = +formData.theoretical_total;
  formData.actual_total = +formData.actual_total;
  formData.difference_total = +formData.difference_total;

  formData.inventorycountitems.forEach((item) => {
    item.theoretical_qty = +item.theoretical_qty;
    item.actual_qty = +item.actual_qty;
    item.difference_qty = +item.difference_qty;
  });

  await Api.inventorycountController.store(formData);
  // 清空表单，
  $table.clearData();
  // 清空表格
  router.go(-1);
};
</script>

<style></style>
